package example.blobapi;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.Transform;
import com.google.appengine.repackaged.org.json.JSONException;
import com.google.appengine.repackaged.org.json.JSONObject;

public class Upload extends HttpServlet {
	private static final Logger log = Logger.getLogger(Upload.class.getName());
	private BlobstoreService blobstoreService = BlobstoreServiceFactory
			.getBlobstoreService();

	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {

		Enumeration headerNames = req.getHeaderNames();
		while (headerNames.hasMoreElements()) {
			String name = (String) headerNames.nextElement();
			System.out.println("header name : " + name);

			String value = req.getHeader(name);
			System.out.println("header value : " + value);
		}
		Enumeration paremeterNames = req.getParameterNames();
		while (paremeterNames.hasMoreElements()) {
			String name = (String) paremeterNames.nextElement();
			System.out.println("parameter name : " + name);
		}
		String path = req.getContextPath();
		System.out.println("getContextPath : " + path);

		int len = req.getContentLength();
		System.out.println("contentLength : " + len);

		String pathInfo = req.getPathInfo();
		String pathTranslated = req.getPathTranslated();
		System.out.println("path : " + pathInfo + " trans : " + pathTranslated);

		/*
		 * try { ServletFileUpload upload = new ServletFileUpload();
		 * FileItemIterator iterator = upload.getItemIterator(req); while
		 * (iterator.hasNext()) { FileItemStream item = iterator.next();
		 * InputStream stream = item.openStream();
		 * 
		 * if (item.isFormField()) { log.warning("Got a form field: " +
		 * item.getFieldName()); } else { log.warning("Got an uploaded file: " +
		 * item.getFieldName() + ", name = " + item.getName());
		 * 
		 * // You now have the filename (item.getName() and the // contents
		 * (which you can read from stream). Here we just // print them back out
		 * to the servlet output stream, but you // will probably want to do
		 * something more interesting (for // example, wrap them in a Blob and
		 * commit them to the // datastore). int fileLen = 0; byte[] buffer =
		 * new byte[8192]; while ((fileLen = stream.read(buffer, 0,
		 * buffer.length)) != -1) { //res.getOutputStream().write(buffer, 0,
		 * len); } BlobInfo blobInfo;
		 * 
		 * 
		 * 
		 * } }
		 * 
		 * res.setContentType("text/plain"); res.getWriter().println(
		 * "Upload Complete"); } catch (Exception e) {
		 * 
		 * }
		 */

		// Iterator itor = map.entrySet().iterator();
		// while(itor.hasNext()) {
		// Entry set = (Entry)itor.next();
		// System.out.println("key : " + set.getKey());
		// System.out.println("value : " + set.getValue());
		// }
		Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
		BlobKey blobKey = null;
		Iterator<String> keyItor = blobs.keySet().iterator();
		String key = null;
		while (keyItor.hasNext()) {
			key = keyItor.next();
			System.out.println("blob key : " + key);
			blobKey = blobs.get(key);
		}

		if (blobKey == null) {
			res.sendRedirect("/");
		} else {

			JSONObject jsonObj = new JSONObject();
			String imageUrl = "";
			BlobInfoFactory blobInfoFactory = new BlobInfoFactory();
			BlobInfo blobInfo = blobInfoFactory.loadBlobInfo(blobKey);

			log.warning("ContentType : " + blobInfo.getContentType());

			if (blobInfo.getFilename().endsWith(".jpg")) {
				ImagesService imagesService = ImagesServiceFactory
						.getImagesService();
				imageUrl = imagesService.getServingUrl(blobKey);
				try {
					jsonObj.put("imageurl", imageUrl);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			res.setContentType("text/plain");

			try {
				jsonObj.put("key", blobKey.getKeyString());
				jsonObj.put("filename", blobInfo.getFilename());
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			res.getWriter().println(jsonObj.toString());
			// res.sendRedirect("/");
			// res.sendRedirect("/serve?blob-key=" + blobKey.getKeyString());
		}
	}
}